<template>
  <div class="department-container">
    <div class="app-container">
      <el-card class="box-card department_box">
        <DeptOptions
          :row="company"
          :is-root="true"
          @clickAdd="onClickAdd"
        />
        <!-- 树形 -->
        <el-tree :data="depts" :props="defaultProps" :default-expand-all="true">
          <template v-slot="scope">
            <DeptOptions
              :row="scope.data"
              @clickEdit="onClickEdit"
              @clickAdd="onClickAdd"
              @ondel="loadDepartments"
            />
          </template>
        </el-tree>
      </el-card>

      <!-- 添加部门的弹出框组件 -->
      <DeptAdd
        ref="addDept"
        :show-dialog.sync="dialogVisible"
        :row="deptRow"
        @addSuccess="loadDepartments"
      />
    </div>
  </div>
</template>

<script>
import { getDepartments } from '@/api/departments'
import { listToTree } from '@/utils'
import DeptOptions from './components/deptOptions.vue'
import DeptAdd from './components/deptAdd.vue'
export default {
  name: 'Departments',
  components: {
    DeptOptions,
    DeptAdd
  },
  data() {
    return {
      defaultProps: {
        label: 'name' // 配置渲染的数据字段(默认渲染的数据字段是label)
      },
      depts: [],
      company: {}, // 记录公司信息
      dialogVisible: false,
      deptRow: {}
    }
  },

  created() {
    this.loadDepartments()
  },

  methods: {
    async loadDepartments() {
      const res = await getDepartments()
      this.company = { name: res.companyName, manager: '负责人', children: listToTree('', res.depts) }
      this.depts = listToTree('', res.depts)
    },
    // 子组件点击了添加触发
    onClickAdd(data) {
      this.dialogVisible = true
      this.deptRow = data
    },

    // 子组件点击了编辑触发
    onClickEdit(data) {
      this.dialogVisible = true
      this.deptRow = data
      setTimeout(() => {
        this.$refs.addDept.setForm()
      })
    }
  }
}
</script>

<style scoped lang="scss">
.department_box{
  .el-tree{
    margin-top: 10px;
    padding-top: 5px;
    border-top: 1px solid #ccc;

  }
}

</style>
